<?php

class DatabaseConnector
{
    protected static $connector = null;
    private static $counter = 0;

    //将构造方法私有化，禁止用户从外部直接通过 new 来创建
    private function __construct($config = []) {
        self::$counter++;
    }

    //提供静态方法来创建对应的实例对象，注意当中无法使用 $this
    public static function getConnector()
    {
        if (self::$connector) return self::$connector;

        return self::$connector = new self(["host" => "127.0.0.1"]);
    }

    //判断实例化了多少次
    public function connect()
    {
        echo "connected " . self::$counter . " times \n";
    }

    //不让通过 clone 来创建对象
    protected function __clone()
    {
        // TODO: Implement __clone() method.
    }

    protected function __wakeup()
    {
        // TODO: Implement __wakeup() method.
    }
}

//测试1：不允许调用私有构造函数, 会报错
//$conn = new DatabaseConnector();
//$conn->connect();

//测试2
$conn2 = DatabaseConnector::getConnector();
$conn2->connect();

//第二次调用
$conn3 = DatabaseConnector::getConnector();
$conn3->connect();